//
//  CustomizeLoverViewController.m
//  Molian
//
//  Created by 胡津 on 4/6/2015.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "CustomizeLoverViewController.h"
#import "CustomizeLoverCell.h"
#import "MLUserDataViewController.h"
#import "TimeUtils.h"
#import "UIScrollView+DXRefresh.h"

// 每次拉取的用户数目
#define USER_NUM_PER_TIME 50

@interface CustomizeLoverViewController ()<UITableViewDataSource, UITableViewDelegate>
// 好友申请列表
@property (nonatomic, strong)NSMutableArray *friendApplyList;

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)Utils * uview;

// 当前分页
@property NSUInteger currentPage;

@end

@implementation CustomizeLoverViewController
{
    MLCustomizationRecord *call;
    NSTimer *_timeTimer;
}

-(void)cmd:(NSNotification *)notification
{
//    NSDictionary *dic=[notification userInfo];
//    EMMessage *message = [dic objectForKey:@"message"];
//    EMCommandMessageBody *body= message.messageBodies.lastObject;

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    if (_timeTimer) {
        [_timeTimer invalidate];
        _timeTimer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"情感热线";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [self refreshUsers];
    [AVAnalytics event:@"情感热线（无独团）"]; // 通知服务器一个点击事件。

    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.tableHeaderView = [[UIView alloc] init];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
    [self.view addSubview:self.tableView];
    self.uview = [[Utils alloc]init];
    [_uview viewControllerPrompt:self.view.bounds Text:@"没有情感热线~" Image:[UIImage imageNamed:@"xinlianren_nul"]];
    [self. view addSubview:_uview.viewPrompt];
    if ([self.friendApplyList count] == 0) {
        _uview.viewPrompt.hidden = NO;
    }else{
        _uview.viewPrompt.hidden = YES;
    }
    
    self.friendApplyList = [NSMutableArray array];
    //上拉加载
    [self.tableView addFooterWithTarget:self action:@selector(loadCustomizationRecordData)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callOk:) name:@"callOk" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
    

    
    _timeTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(relodata) userInfo:nil repeats:YES];

}

-(void)relodata
{
    [self.tableView reloadData];
}

// 加载好友申请列表
- (void)refreshUsers {
    [self.friendApplyList removeAllObjects];
    // 当前分页归零
    self.currentPage = 0;
    // 加载用户数据
    [self loadCustomizationRecordData];
}

- (void)loadCustomizationRecordData {

    AVQuery *CustomizationRecord = [MLCustomizationRecord query];
    [CustomizationRecord orderByDescending:@"updatedAt"];
    [CustomizationRecord includeKey:@"sponsor"];
    [CustomizationRecord whereKey:@"type" notEqualTo:[MLUser currentUser].gender == MLUserGender_MALE ? [NSNumber numberWithInt:1]:[NSNumber numberWithInt:2]];
    [CustomizationRecord whereKey:@"sponsor" notEqualTo:[MLUser currentUser]];
    [CustomizationRecord whereKey:@"status" equalTo:[NSNumber numberWithInt:MLCustomizationRecordStatus_NORMAL]];
    
    // 控制分页获取
    CustomizationRecord.limit = USER_NUM_PER_TIME;
    CustomizationRecord.skip = self.currentPage * USER_NUM_PER_TIME;
    [CustomizationRecord findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        [self.tableView footerEndRefreshing];
        if (!error) {
            for (MLCustomizationRecord *article in objects) {
                // 根据日期计算距今的时间,以分钟计
                double pastSeconds = [[NSDate date]timeIntervalSinceDate:article.createdAt];
                NSInteger pastMinute = pastSeconds/60;
                if (pastMinute >=10) {
                    [AVAnalytics event:@"情感热线（无独团）作废数"]; // 通知服务器一个点击事件。
                    [article deleteInBackground];
                }else{
                    [self.friendApplyList addObject:article];
                }
            }
            
            
            self.currentPage ++;

            if ([self.friendApplyList count] == 0) {
                _uview.viewPrompt.hidden = NO;
            }else{
                _uview.viewPrompt.hidden = YES;
                [self.tableView reloadData];
            }
        } else {
            // 加载出错, 提示
            [HUD Prompt:@"网络异常" ];
        }
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"FriendApplyCell";
    CustomizeLoverCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[CustomizeLoverCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    // 如果列表为空直接返回
    if ([self.friendApplyList count] == 0) {
        return cell;
    }
    MLCustomizationRecord *friendApply = self.friendApplyList[indexPath.row];
    MLUser *applier = (MLUser *)friendApply.sponsor;

    cell.friendApply = friendApply;
    cell.userNameLabel.text = applier.nickname;
   // [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:applier.avatar.url] placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
    if (!applier.subAvatar || [applier.subAvatar isEqualToString:@""]) {
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:applier.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        
    }else{
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:applier.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
    }
    [cell.userAgeLabel setTitle:[NSString stringWithFormat:@"%ld", (long)[applier getUserAge]] forState:UIControlStateNormal];
    if (applier.gender == MLUserGender_MALE) {
        [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
    } else {
        [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"girl_age"] forState:UIControlStateNormal];
    }
    
    NSString *city = applier.selectCity?applier.selectCity:@"";
    NSString *strH = applier.height?[NSString stringWithFormat:@"%ldcm",(long)applier.height]:@"";
    NSString *title = [NSString stringWithFormat:@"%@  %@",city,strH];
    [cell.userSeriesLabel setTitle:title forState:UIControlStateNormal];
    cell.userSeriesLabel.selected = YES;
   
  
    cell.callPhone.tag = indexPath.row+500;
    [cell.callPhone addTarget:self action:@selector(callPhone:) forControlEvents:UIControlEventTouchUpInside];

    cell.priceLabel.text = [NSString stringWithFormat:@"  通话资费:%.0f金币/分钟",(friendApply.price*10)];
    // 重置remarkLabel高度
    cell.timeLabel.text = [TimeUtils getPastTimeWithDate:friendApply.createdAt];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return  cell;
}



-(void)hud:(NSString *)str
{
    HUD*hud = [[HUD alloc]init];
    [hud HUDImage:nil Title:@"提示" Content:str CANCEL:@"取消" Confirm:@"再看看"];
    hud.Confirm  = ^{
        // 刷新列表
        [self refreshUsers];
    };
    hud.Cancel = ^{
        NSLog(@"取消");
    };
    [self.view addSubview:hud];
}

-(void)callOk:(NSNotification *)notification
{
    id object = notification.object;
    if ([[object objectForKey:@"status"] isEqualToString:@"NO"]) {
        call.status = MLCustomizationRecordStatus_DISABLE;
        call.winner = [MLUser currentUser];
        [call saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [self.friendApplyList removeObject:call];
                [self.tableView reloadData];
            }else{
                [Utils saveToDefaults:@"NO" forKey:@"callCustomizeLoverPhone"];
                [HUD Prompt:@"失败请重新尝试"];
            }
        }];
    }else if ([[object objectForKey:@"status"] isEqualToString:@"YES"]){
        [self refreshUsers];
//        call.cost = [[object objectForKey:@"cost"] floatValue];
//        call.time = [[object objectForKey:@"time"] floatValue];
//        
//        [call saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//            if (succeeded) {
//                [self refreshUsers];
//            }else{
//                [Utils saveToDefaults:@"NO" forKey:@"callCustomizeLoverPhone"];
//                [HUD Prompt:@"失败请重新尝试"];
//            }
//        }];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MLCustomizationRecord *friendApply = self.friendApplyList[indexPath.row];
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData = (MLUser *)friendApply.sponsor;
    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
    
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.friendApplyList count];;
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 每个cell的头部间距
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    //每个cell的底部间距
    return CGFLOAT_MIN;
}

- (void)dealloc {
    if (_timeTimer) {
        [_timeTimer invalidate];
        _timeTimer = nil;
    }
     [[NSNotificationCenter defaultCenter] removeObserver:self];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callOk" object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cmd" object:nil];
    [self.tableView removeFooter];
}

@end
